<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 支付接口
 */
namespace app\allwin\controller\api\v4;
use app\allwin\controller\api\Base;
use app\allwin\model\AllwinShopOrder;
use app\allwin\model\Bank;
use app\allwin\model\AllwinShop;
use app\allwin\model\AllwinConfig;
use app\allwin\model\CouponUser;
use app\allwin\model\MchId;
use app\allwin\model\Vip;
use app\common\model\SystemMemberForm;
use app\common\model\SystemUser;
use app\common\facade\WechatPay;

class Shopdopay extends Base{

    /**
     * 初始化当前应用是否登录
     * @return void
     */
    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
    }

    /**
     * 购买商品
     */
    public function index(){
        if (request()->isPost()) {
            $param['shop_id']  = $this->request->param('shop_id/d');
            $param['telphone'] = $this->request->param('telphone/s','');
            $param['message']  = $this->request->param('message','');
            $param['ucode']    = $this->request->param('ucode','');
            $param['signkey']  = $this->request->param('signkey');
            $param['sign']     = $this->request->param('sign');
            $sign = $this->apiSign($param);
            if($sign['code'] != 200){
                return enjson($sign['code'],'签名验证失败');
            }
            //判断是否已下架
            $item = AllwinShop::where(['member_miniapp_id' => $this->miniapp_id,'id' => $param['shop_id'],'is_sale' => 1,'is_del' => 0])->field('store_id,name,title,warehouse_num,points,vip_price,market_price,sell_price,coupon_id,img,notice')->find();
            if(empty($item)){
                return enjson(403,'商品已经下架');
            }
            if($item->warehouse_num <= 0){
                return enjson(403,'商品已售完');
            }
            //读取订单
            $shop_order = AllwinShopOrder::where(['member_miniapp_id' => $this->miniapp_id,'user_id' =>$this->user->id,'shop_id' => $param['shop_id'],'is_del' => 0])->field('paid_at,status,order_no,amount,sell_price')->find();
            $order_no = $this->user->invite_code.order_no();
            if(empty($shop_order)){
                $validate = $this->validate($param,'Dopay.goods');
                if (true !== $validate) {
                    return enjson(403,$validate);
                }
                $sell_price   = $item->sell_price;
                $is_new_order = true;
            }else{
                if($shop_order->paid_at == 1 && $shop_order->status == 0){
                    return enjson(403,'订单未核销,请先去商家核销');
                }
                if($shop_order->sell_price < $item->sell_price){
                    $shop_order->is_del = 1;
                    return enjson(403,'订单已失效,请重新下单');
                }else{
                    $shop_order->order_no = $order_no;
                }
                $shop_order->save();
                $sell_price   = $shop_order->amount;
                $is_new_order = false;
            }
            //判断扣除积分
            $points       = 0;  //扣除积分
            $points_price = 0;  //扣除金额
            if($item->points){
                $bank = Bank::where(['member_miniapp_id' => $this->miniapp_id,'user_id' => $this->user->id])->field('shop_money')->find();
                if(!empty($bank->shop_money)){
                    if($bank->shop_money >= $item->points){
                        $points_price = money($item->points/100);
                        $points       = $item->points;
                    }else{
                        $points_price = money($bank->shop_money/100);
                        $points       = $bank->shop_money;
                    }
                }
            }
            //判断是否VIP
            $vip_price = 0;
            $vip = Vip::where(['user_id' => $this->user->id,'state' => 1,'is_lock' => 0])->count();
            if($vip && $item['vip_price']){
                $vip_price = $item->vip_price;
            }
            //优惠券
            $coupon_price = 0;
            if($item->coupon_id){
                $condition[] = ['uid','=',$this->user->id];
                $condition[] = ['member_miniapp_id','=',$this->miniapp_id];
                $condition[] = ['is_end','=',0];
                $condition[] = ['endtime','>=',time()];
                $condition[] = ['coupon_id','=',$item->coupon_id];
                $coupon = CouponUser::where($condition)->order('id desc')->find();
                if($coupon){
                    $coupon_price = empty($item->coupon) ? 0 : AllwinShop::calculatePrice($item->sell_price,$coupon);
                }
            }
            $amount  = money($sell_price-$vip_price-$points_price-$coupon_price);
            $thrifty = money($item->market_price - $amount); //节省多少钱
            //唤醒微信支付参数
            $payparm = [
                'openid'     => $this->user->miniapp_uid,
                'miniapp_id' => $this->miniapp_id,
                'name'       => $item->name,
                'order_no'   => $order_no,
                'total_fee'  => $amount <= 0 ? 1 : $amount*100,
                'notify_url' => api(4,'allwin/shopnotify/index',$this->miniapp_id),
            ];
            //读取配置
            $setting = AllwinConfig::getConfig($this->miniapp_id);
            if($setting->is_psp == 1){
                if(empty($item->store->mch_id)){
                    $default_mchid = MchId::getMch(0, $this->miniapp_id);  //默认收款账户
                }else{
                    $default_mchid = MchId::getMch($item->store->mch_id);  //商户的商户号
                    $payparm['profit_sharing'] = $setting->is_wechat_profitsharing == 1 ? 'Y' : 'N';
                }
                if(empty($default_mchid)) {
                    return enjson(403,'未找到商户号');
                }
                $payparm['mchid'] = $default_mchid->mchid;
            }
            $ispay = WechatPay::orderPay($payparm);
            if ($ispay['code'] == 0) {
                return enjson(403,$ispay['msg']);
            }
            //判断是否新订单
            $rel = true;
            if($is_new_order){
                $param['user_id']           = $this->user->id;
                $param['member_miniapp_id'] = $this->miniapp_id;
                $param['store_id']          = $item->store_id;
                $param['share_uid']         = SystemUser::isInvite($param['ucode']);
                $param['sell_price']        = $item->sell_price;
                $param['amount']            = $amount;
                $param['thrifty']           = $thrifty;
                $param['points']            = $points;
                $param['shop_cache']        = $item->toJson();
                $rel = AllwinShopOrder::insertOrder($param,$order_no);
            }
            if(empty($rel)){
                return enjson(204,'购买商品失败');
            }
            return enjson(200,'成功',$ispay['data']);
        }
    }

    /**
     * 读取单个商品信息
     * @param integer $id 商品ID
     * @return void
     */
    public function cart(){
        $param['id']      = $this->request->param('id/d',0);
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        //查找商品SPU
        $item = AllwinShop::where(['is_sale'=>1,'id' => $param['id'],'member_miniapp_id' => $this->miniapp_id])->field('id,store_id,coupon_id,name,title,img,points,sell_price,market_price,end_time,vip_price')->find();
        if(empty($item)){
            return json(['code'=>403,'msg'=>'没有内容']);
        }
        $item['market_price'] = money($item['market_price']);
        $item['sell_price']   = money($item['sell_price']);
        $item['img']          = $item['img'].'?x-oss-process=style/500';
        $item['coupon_id']    = $item->coupon_id;
        $item['coupon_price'] = 0;
        $item['coupon_user_price'] = 0;
        if($item->coupon_id){
            $item['coupon_price'] = money(empty($item->coupon) ? 0 : AllwinShop::calculatePrice($item->sell_price,$item->coupon));
            //用户已领取赠品
            $condition[] = ['uid','=',$this->user->id];
            $condition[] = ['member_miniapp_id','=',$this->miniapp_id];
            $condition[] = ['is_end','=',0];
            $condition[] = ['endtime','>=',time()];
            $condition[] = ['coupon_id','=',$item->coupon_id];
            $coupon = CouponUser::where($condition)->order('id desc')->find();
            if($coupon){
                $item['coupon_user_price'] = money(AllwinShop::calculatePrice($item->sell_price,$item->coupon));
            }
        }
        $item['telphone']  = $this->user->phone_uid;
        //判断是否会员
        $vip = Vip::where(['user_id' => $this->user->id,'state' => 1,'is_lock' => 0])->count();
        $item['is_vip']  = $vip ? 1 : 0;
        $vip_price       = $vip ? $item['vip_price'] : 0; //判断会员是否优惠
        //判断积分
        $item['points_price']      = money($item->points/100);
        $item['bank_points_price'] = 0;
        $item['bank_points']       = 0;
        if($item->points > 0){
            $bank = Bank::where(['user_id' => $this->user->id,'member_miniapp_id' => $this->miniapp_id])->field('shop_money')->find();
            if(empty($bank->shop_money)){
                $item['shop_money'] = 0;
            }else{
                if($bank->shop_money >= $item->points){
                    $item['bank_points_price'] = money($item->points/100);
                    $item['bank_points']       = $item->points;
                }else{
                    $item['bank_points_price'] = money($bank->shop_money/100);
                    $item['bank_points']       = $bank->shop_money;
                }
                $item['shop_money'] = $bank->shop_money;
            }
        }
        $item['amount']  = money($item['sell_price'] - $vip_price - $item['bank_points_price'] - $item['coupon_user_price']);
        $thrifty = money($item['market_price'] - $item['amount']);
        $item['thrifty'] = $thrifty > 0 ? $thrifty : 0;
        if(empty($item)){
            return enjson(403,'没有内容');
        }else{
            return enjson(200,'成功',$item);
        }
    }
}